package pers.hxy.lookweather.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.view.QWeather;

import java.util.List;

import pers.hxy.lookweather.R;

/**
 * 根据用户输入从网上进行搜索，
 * 输入的location说明：
 * 需要查询地区的名称，
 * 支持文字、
 * 以英文逗号分隔的经度,纬度坐标（十进制，最多支持小数点后两位）、
 * LocationID或Adcode（仅限中国城市）。
 * 例如 location=北京 或 location=116.41,39.92
 */
public class SearchLocationActivity extends AppCompatActivity {
    private static final String TAG = "SearchLocationActivity";
    private EditText etSearch;
    private TextView tvResult;
    private Button btnSelect;
    private Button btnCancel;
    private Handler mSearchHandler;
    private List<GeoBean.LocationBean> mLocationBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_search_location);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        etSearch = findViewById(R.id.et_search_location);
        tvResult = findViewById(R.id.tv_searched_location);
        btnSelect = findViewById(R.id.button_select_searched_location);
        btnCancel = findViewById(R.id.button_cancel_search_location);
        mSearchHandler = new Handler(getMainLooper());
        mLocationBeanList = null;

        btnSelect.setOnClickListener( v -> {
            // 只有当list的size大于0时按钮才可用，所以不用进行检查
            GeoBean.LocationBean locationBean = mLocationBeanList.get(0);
            Intent intent = new Intent();
            intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_BEAN, new Gson().toJson(locationBean));
            intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_NAME, String.join("/",
                    locationBean.getCountry(), locationBean.getAdm1(), locationBean.getAdm2(), locationBean.getName()));
            intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_ID, locationBean.getId());
            setResult(RESULT_OK, intent);
            finish();
        });

        btnCancel.setOnClickListener( v -> {
            setResult(RESULT_CANCELED);
            finish();
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.d(TAG, "onTextChanged: " + s + " " + start + " " + before + " " + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String location = s.toString().trim();
                Log.d(TAG, "afterTextChanged: '" + location + "'");

                // 移除之前的搜索请求，防止频繁地进行网络搜索
                mSearchHandler.removeCallbacksAndMessages(null);

                if (location.isEmpty()) {
                    onReceiveSearchResult(null);
                    return;
                }

                mSearchHandler.postDelayed(() -> {
                    Log.d(TAG, "search location: " + location);
                    QWeather.getGeoCityLookup(SearchLocationActivity.this, location, new QWeather.OnResultGeoListener() {
                        @Override
                        public void onError(Throwable throwable) {
                            runOnUiThread(() -> {
                                onReceiveSearchResult(null);
                            });
                        }

                        @Override
                        public void onSuccess(GeoBean geoBean) {
                            runOnUiThread(() -> {
                                onReceiveSearchResult(geoBean.getLocationBean());
                            });
                        }
                    });
                }, 500); // 输入完成并且500毫秒内没有改变输入时进行搜索

            }
        });

        onReceiveSearchResult(null);
    }

    private void onReceiveSearchResult(List<GeoBean.LocationBean> locationBeans) {
        mLocationBeanList = locationBeans;
        if (locationBeans == null || locationBeans.isEmpty()) {
            btnSelect.setEnabled(false);
            tvResult.setText("数量：0");
            return;
        }
        StringBuilder s = new StringBuilder("数量：" + locationBeans.size() + '\n');
        for (int i = 0; i < locationBeans.size(); i++) {
            GeoBean.LocationBean bean = locationBeans.get(i);
            s.append(i + 1).append(": ")
                    .append(String.join("/", bean.getCountry(), bean.getAdm1(), bean.getAdm2(), bean.getName(), bean.getId()))
                    .append('\n');
        }
        tvResult.setText(s.toString());
        btnSelect.setEnabled(true);
    }
}
